﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Workbench.Shared
{
    public static class ObservableCollectionExtensions
    {
        public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            foreach (var item in items)
                collection.Add(item);
        }

        public static void ForEach<T>(this ObservableCollection<T> collection, Action<T> action)
        {
            foreach (var item in collection)
                action(item);
        }

        public static void SubscribeItemPropChange<T>(this ObservableCollection<T> collection, string propertyName, Action<T> handler) where T : class, INotifyPropertyChanged
        {
            PropertyChangedEventHandler propChangedHandler = (sender, args) =>
            {
                if (string.Compare(args.PropertyName, propertyName, false) == 0)
                {
                    handler(sender as T);
                }
            };

            collection.CollectionChanged += (sender, args) =>
            {
                if (args.NewItems != null)
                {
                    foreach (T item in args.NewItems.Cast<T>())
                        item.PropertyChanged += propChangedHandler;
                }
                if (args.OldItems != null)
                {
                    foreach (T currentBaseForm in args.OldItems.Cast<T>())
                        currentBaseForm.PropertyChanged -= propChangedHandler;
                }
            };
        }
    }
}
